<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>
      <!-- 级联选择器 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
            <el-cascader
            v-model="selectedKeys"
            :options="cascaderOptions"
            :props="cascaderPops"
            @change="handleChange"
            clearable></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isDisable" type="primary" size="mini" @click="addParams">添加参数</el-button>
          <!-- 表格区域 -->
          <el-table :data="manyParams" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                v-for="(item,i) in scope.row.attr_vals"
                :key="i"
                @close="handleClose(scope.row,i)"
                closable>
                {{item}}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deletParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="isDisable" type="primary" size="mini" @click="addParams">添加属性</el-button>
          <el-table :data="onlyParams" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                v-for="(item,i) in scope.row.attr_vals"
                :key="i"
                @close="handleClose(scope.row,i)"
                closable>
                {{item}}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deletParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/添加属性 对话框 -->
    <el-dialog
      :title="'添加'+isActiveName"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsFromClosed">
      <!-- 内容区域 -->
      <el-form :model="addParamsForm" :rules="addParamsrules" ref="addParamsForm" label-width="100px">
        <el-form-item :label="isActiveName" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 取消/确定按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsSure">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑修改参数对话框 -->
    <el-dialog
      :title="'修改'+isActiveName"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editParamsFromClosed">
      <!-- 内容区域 -->
      <el-form :model="editParamsForm" :rules="editParamsrules" ref="editParamsForm" label-width="100px">
        <el-form-item :label="isActiveName" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 取消/确定按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  created () {
    this.getGoodsCategory()
  },
  data () {
    return {
      // 级联选择器指定选项数组
      selectedKeys: [],
      // options属性指定选项数组即可渲染出一个级联选择器
      cascaderOptions: [],
      // 级联选择器配置选项
      cascaderPops: {
        // 指定的值
        value: 'cat_id',
        // 页面上能看见的值
        label: 'cat_name',
        chlidren: 'children',
        // hover时触发子菜单
        expandTrigger: 'hover'
      },
      // 绑定的是name属性值
      activeName: 'many',
      // 分类id
      categoryId: 0,
      // 动态参数
      manyParams: [],
      // 静态属性
      onlyParams: [],
      // 控制显示添加参数对话框显示与隐藏
      addParamsDialogVisible: false,
      // 添加参数表单绑定的属性
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数表单验证规则
      addParamsrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制编辑对话框的显示与隐藏
      editParamsDialogVisible: false,
      // 绑定的编辑对话框的值
      editParamsForm: {
        attr_name: ''
      },
      // 编辑对话框表单校验规则
      editParamsrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取商品列表数据--渲染到级联选择器中
    async getGoodsCategory () {
      // 向服务器返送axios请求
      const { data: res } = await this.$http.get('categories')
      this.cascaderOptions = res.data
    },
    // 级联选择器改变触发
    handleChange () {
      this.getCategoryParams()
    },
    // tab 被选中时触发
    handleClick () {
      console.log(this.activeName)
      console.log(this.selectedKeys)
      // 被触发时获取数据
      this.getCategoryParams()
    },
    // 获取分类参数
    async getCategoryParams () {
      // 先判断级联选择框中选择的是否是三级分类，不是就清空
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyParams = []
        this.onlyParams = []
        return
      }

      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // 在得到分类参数时就把attr_vals字符串转换成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 在每个元素下添加一个属性控制输入框显示与隐藏
        item.inputVisible = false
        item.inputValue = ''
      })

      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyParams = res.data
      } else {
        this.onlyParams = res.data
      }
    },
    // 点击添加参数，弹出对话框
    addParams () {
      // 显示弹框
      this.addParamsDialogVisible = true
    },
    // 点击确定添加参数事件
    addParamsSure () {
      // 表单预校验
      this.$refs.addParamsForm.validate(async valid => {
        // valid==false校验失败直接返回
        if (!valid) return
        // 校验成功
        // 发起请求添加参数到数据库中
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
          { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName }
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        // 重新获取数据，刷新页面
        this.getCategoryParams()
        // 关闭对话框
        this.addParamsDialogVisible = false
      })
    },
    // 监听添加参数对话框关闭事件
    addParamsFromClosed () {
      // 重置表单
      this.$refs.addParamsForm.resetFields()
    },
    // 点击编辑修改参数名称
    editParams (row) {
      console.log(this.cateId)
      this.editParamsForm = row
      console.log(this.editParamsForm.attr_id)
      // 获取这一行的数据，把值赋值个编辑参数的表单对象里面，再渲染到表单里面
      this.editParamsForm.attr_name = row.attr_name
      // 弹出编辑对话框
      this.editParamsDialogVisible = true
    },
    // 监听编辑对话框的关闭事件
    editParamsFromClosed () {},
    // 点击编辑参数确定修改事件
    editParamsSure () {
      // 表单预验证
      this.$refs.editParamsForm.validate(async valid => {
        if (!valid) return
        // 表单验证成功向服务器发送请求修改数据添加到数据库中
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        // 修改参数成功
        this.$message.success('更新数据成功')
        // 关闭编辑对话框
        this.editParamsDialogVisible = false
      })
    },
    // 点击删除按钮删除参数
    async deletParams (row) {
      // 弹出提示框
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户点击的是取消
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 用户点击的是确定-发送请求，删除参数
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除参数成功')
      // 更新分类参数数据
      this.getCategoryParams()
    },
    // expand展开或关闭事件
    // exchange (row, expandedRows) {
    //   console.log(row)
    //   console.log(expandedRows)
    // },
    // input输入框失去焦点和鼠标抬起事件处理函数
    handleInputConfirm (row) {
      // 如果inputValue去除空格长度为0时清空input输入框的值
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        // 失去焦点和鼠标按下回车时显示button
        row.inputVisible = false
        return false
      }

      // 用户输入了真实的内容
      // 把值push到attr_vals
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      // 向服务器发送请求提交参数保存到数据库中
      this.saveAttrVals(row)
    },
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改参数成功')
    },
    showInput (row) {
      // 点击button时把inputVisible的值改为true显示输入框
      row.inputVisible = true
      // $nextTick方法是重新渲染后的才会执行回调函数中的代码--重新渲染后才有input这个元素，才能让input获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 监听tag标签关闭事件
    handleClose (row, index) {
      console.log(row)
      // splice会修改原数组
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 返回一个布尔值禁用button为true为禁用，否则为false不禁用
    isDisable () {
      // 如果长度为3说明选择的是三级分类就不禁用按钮
      if (this.selectedKeys.length === 3) {
        return false
      }
      // 长度不为3说明选择的不是三级分类，禁用按钮
      return true
    },
    // 当前选中的三级分类id
    cateId () {
      if (this.selectedKeys.length === 3) {
        // 返回最后一个三级分类id
        return this.selectedKeys[2]
      }
      return null
    },
    // 动态获取对话框显示文本
    isActiveName () {
      // 如果this.activeName=many,返回动态动态参数
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  margin: 15px 0;
  width: 30%;
}
.el-table{
  margin-top: 15px;
}
.el-tag{
  margin-right: 15px;
}
.input-new-tag {
  width:120px;
}
</style>
